package net.cardgame.orcalecard;

import java.util.ArrayList;
import java.util.Date;

import jp.jma.oraclecard.MyApplication;
import jp.jma.oraclecard.R;
import net.cardgame.oraclecard.service.DownloadUnzipObject;
import net.cardgame.oraclecard.service.ServiceDownload;
import net.cardgame.oraclecard.service.ServiceDownloadListener;
import net.cardgame.orcalecard.bean.DeckBean;
import net.cardgame.orcalecard.bean.SettingApp;
import net.cardgame.orcalecard.pref.SecurePreferences;
import net.cardgame.orcalecard.utils.ConstantValue;
import net.cardgame.orcalecard.utils.Sort;
import net.cardgame.orcalecard.utils.Utils;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.novoda.imageloader.core.ImageManager;
import com.novoda.imageloader.core.OnImageLoadedListener;
import com.novoda.imageloader.core.model.ImageTagFactory;

public class GridViewAdapter extends ArrayAdapter<DeckBean> implements
		OnImageLoadedListener {
	private ImageManager imageManager;
	private ImageTagFactory imageTagFactory;
	Activity activity;
	ArrayList<DeckBean> listDeckBean;
	LinearLayout.LayoutParams paramsHeader, paramsFooter;
	int size = 0, loaded = 0;
	Date dateNow;
	private boolean image_load_finished = false;
	private ServiceDownloadListener downloadListener;

	public GridViewAdapter(Activity context, ArrayList<DeckBean> listDeckBean) {
		super(context, 0);
		downloadListener = (ServiceDownloadListener) context;
		activity = context;
		this.listDeckBean = listDeckBean;
		this.size = listDeckBean.size();
		dateNow = new Date();
		initImageLoader();
		checkLoadFinished();
	}

	private void checkLoadFinished() {
		SecurePreferences appPreferences = new SecurePreferences(activity,
				ConstantValue.APP_PREFERENCES,
				ConstantValue.PREFERENCES_SECRET_KEY, true);
		if (appPreferences.containsKey(ConstantValue.KEY_LOAD_FINISHED_TOPPAGE))
			image_load_finished = true;
	}

	public ArrayList<DeckBean> sortDeckBean(int type) {
		switch (type) {
		case SettingApp.SORT_BY_BUY:
			listDeckBean = Sort.sortByBuy(listDeckBean);
			break;
		case SettingApp.SORT_BY_RELEASE:
			listDeckBean = Sort.sortByRelease(listDeckBean);
			break;
		case SettingApp.SORT_BY_USED:
			listDeckBean = Sort.sortByLastUsed(listDeckBean);
			break;
		default:
			break;
		}
		this.notifyDataSetChanged();
		return listDeckBean;
	}

	/* Function display percent downloading of a DeckBean */
	public void setPercentDownloaded(int position, int percentDownloaded) {
		listDeckBean.get(position).percentDownloaded = percentDownloaded;
		this.notifyDataSetChanged();
	}

	public void updateStatus(ArrayList<DeckBean> listDeck) {
		this.listDeckBean = listDeck;
		this.notifyDataSetChanged();
	}

	public void setPercent(int decId, int percent) {
		for (DeckBean deckBean : listDeckBean) {
			if (deckBean.deckId == decId) {
				deckBean.percentDownloaded = percent;
				this.notifyDataSetChanged();
				downloadListener.onUpdateProgressListener(percent, 0, decId);
				if (percent == 100) {
					downloadListener
							.onFinishedListener(new DownloadUnzipObject(
									deckBean.deckId, 0, "", ""));
				}
				return;
			}
		}
	}

	/* Function unlock a DeckBean by position */
	public void unlockDeckBean(int position) {
		listDeckBean.get(position).isUnlock = true;
		this.notifyDataSetChanged();
	}

	public void unlockDeckBeanById(int deckId) {
		for (DeckBean dec : listDeckBean) {
			if (dec.deckId == deckId) {
				dec.isUnlock = true;
				return;
			}
		}
	}

	/* get GridView item total */
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		if (size % 3 == 0)
			return size;
		else
			return size + (3 - size % 3);
	}

	/* Get item gridview by position */
	@Override
	public DeckBean getItem(int position) {
		// TODO Auto-generated method stub
		return listDeckBean.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	private String idToString(int id) {
		return id < 10 ? "0" + id : "" + id;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.widget.ArrayAdapter#getView(int, android.view.View,
	 * android.view.ViewGroup)
	 */
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub

		View row = convertView;
		ViewHolder holder;
		/*
		 * inflate layout
		 */
		if (row == null) {
			LayoutInflater inflator = activity.getLayoutInflater();
			row = inflator.inflate(R.layout.item_gridview_top_header, null);
			holder = new ViewHolder();
			holder.progressbar = (ProgressBar) row
					.findViewById(R.id.progressbar);
			holder.progressbar.setMax(100);
			holder.imgViewCategory = (ImageView) row
					.findViewById(R.id.image_category_option_gridview);
			holder.imgTitle = (ImageView) row
					.findViewById(R.id.image_title_option_gridview);
			holder.imgNew = (ImageView) row
					.findViewById(R.id.image_new_option_gridview);
			holder.imgLock = (ImageView) row
					.findViewById(R.id.image_lock_option_gridview);
			holder.imgBackground = (ImageView) row
					.findViewById(R.id.image_bg_option_gridview);
			holder.txtHeader = (TextView) row.findViewById(R.id.txt_header);
			paramsHeader = (LinearLayout.LayoutParams) holder.txtHeader
					.getLayoutParams();
			holder.txtFooter = (TextView) row.findViewById(R.id.txt_footer);
			paramsFooter = (LinearLayout.LayoutParams) holder.txtFooter
					.getLayoutParams();
			row.setTag(holder);
		} else {
			holder = (ViewHolder) row.getTag();
		}
		/*
		 * Set bacground resource
		 */
		if (position % 3 == 0) {
			holder.imgBackground.setImageResource(R.drawable.left_bg);
		} else if (position % 3 == 1) {
			holder.imgBackground.setImageResource(R.drawable.center_bg);
		} else
			holder.imgBackground.setImageResource(R.drawable.right_bg);
		/*
		 * set image resource
		 */
		if (position < 3)
			holder.txtHeader.setLayoutParams(paramsHeader);
		else
			holder.txtHeader.setLayoutParams(new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.MATCH_PARENT, 0));
		if (position > getCount() - 4)
			holder.txtFooter.setLayoutParams(paramsFooter);
		else {
			holder.txtFooter.setLayoutParams(new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.MATCH_PARENT, 0));
		}
		DeckBean deckBean = new DeckBean();
		try {
			deckBean = listDeckBean.get(position);
		} catch (Exception ex) {
			holder.imgTitle.setImageDrawable(null);
			holder.imgViewCategory.setImageDrawable(null);
			holder.imgLock.setImageDrawable(null);
			holder.imgNew.setImageDrawable(null);
			holder.progressbar.setVisibility(View.INVISIBLE);
			return row;
		}
		if (deckBean.isUnlock || deckBean.isFree)
			holder.imgLock.setImageDrawable(null);
		else {
			holder.imgLock.setImageResource(R.drawable.mypage_lock);
		}
		if (deckBean.releaseDate != null)
			holder.imgNew.setImageResource(R.drawable.new_release);
		else {
			holder.imgNew.setImageDrawable(null);
		}
		String tt = idToString(deckBean.deckId);
		String title = deckBean.pathServerDownload + "/c" + tt + "n.png";
		String strDeck = deckBean.pathServerDownload + "/c" + tt + "i.png";
		setImageTag(holder.imgTitle, title);
		loadImage(holder.imgTitle);
		setImageTag(holder.imgViewCategory, strDeck);
		loadImage(holder.imgViewCategory);

		/* Set percent downloading */
		int percent = deckBean.percentDownloaded;
		if (percent >= 0 && percent < 100) {
			holder.progressbar.setVisibility(View.VISIBLE);
			holder.progressbar.setProgress(percent);
			holder.progressbar.setIndeterminate(false);
		} else {
			holder.progressbar.setVisibility(View.INVISIBLE);
		}
		long diff = dateNow.getTime() - deckBean.releaseDate.getTime();
		int numberOfDay = (int) (diff / 1000 / 60 / 60 / 24);
		// Set is New
		if (deckBean.percentDownloaded == -2 || numberOfDay > 30) {
			holder.imgNew.setVisibility(View.INVISIBLE);
		} else
			holder.imgNew.setVisibility(View.VISIBLE);
		return row;
	}

	static class ViewHolder {
		ImageView imgTitle;
		ImageView imgBackground;
		ImageView imgViewCategory;
		ImageView imgLock;
		ImageView imgNew;
		TextView txtHeader, txtFooter;
		ProgressBar progressbar;
	}

	private void initImageLoader() {
		imageManager = MyApplication.getInstance().getImageLoader();
		imageTagFactory = createImageTagFactory();
	}

	private ImageTagFactory createImageTagFactory() {
		ImageTagFactory imageTagFactory = ImageTagFactory.newInstance();
		imageTagFactory.setHeight(248);
		imageTagFactory.setWidth(188);
		imageTagFactory.setDefaultImageResId(R.drawable.cardi_tranparent);
		imageTagFactory.setErrorImageId(R.drawable.cardi_tranparent);
		imageTagFactory.setSaveThumbnail(true);
		return imageTagFactory;
	}

	private void setImageTag(ImageView view, String url) {
		view.setTag(imageTagFactory.build(url, activity));
		// view.setContentDescription(url);
	}

	private void loadImage(ImageView view) {
		imageManager.getLoader().load(view);
		if (!image_load_finished)
			imageManager.setOnImageLoadedListener(this);
	}

	@Override
	public synchronized void onImageLoaded(ImageView imageview) {
		// TODO Auto-generated method stub
		// Utils.ELog("loaded", imageview.getContentDescription().toString());
		loaded++;
		if (loaded >= 2 * size - 4) {
			// Save sharedreference
			SecurePreferences appPreferences = new SecurePreferences(activity,
					ConstantValue.APP_PREFERENCES,
					ConstantValue.PREFERENCES_SECRET_KEY, true);
			appPreferences.put(ConstantValue.KEY_LOAD_FINISHED_TOPPAGE, "true");
		}
	}

	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			Bundle bundle = intent.getExtras();
			if (bundle.containsKey(ServiceDownload.KEY_MESSAGE_FULL_MEMORY)) {
				downloadListener.onDownloadFailListener(null, bundle
						.getString(ServiceDownload.KEY_MESSAGE_FULL_MEMORY));
				return;
			}
			int deckID = bundle.getInt(ServiceDownload.KEY_DECK_ID);
			int position = bundle.getInt(ServiceDownload.KEY_POSITION);
			int percent = bundle.getInt(ServiceDownload.KEY_PERCENT);
			setPercent(deckID, percent);
			if (bundle.containsKey(ServiceDownload.KEY_STATUS)) {
				boolean finished = bundle
						.getBoolean(ServiceDownload.KEY_STATUS);
				if (!finished) {
					downloadListener.onDownloadFailListener(
							new DownloadUnzipObject(deckID, position, "", ""),
							null);
				}
			}
		}
	};

	public void registryBroadcast() {
		LocalBroadcastManager.getInstance(activity).registerReceiver(
				mBroadcastReceiver,
				new IntentFilter(ConstantValue.ACTION_DOWNLOAD));
	}

	public void unRegistryBroadcast() {
		LocalBroadcastManager.getInstance(activity).unregisterReceiver(
				mBroadcastReceiver);
	}

}
